package controller

import (
	//"cloud.hubbleye.alertcenter.service/weixin"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"io/ioutil"
	"net/http"
	"ops.alert.center.service/internal/middleware"
	"ops.alert.center.service/internal/model"
	"ops.alert.center.service/internal/util"
	"strconv"
	"strings"
	"time"
)

var count int

func Health(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("/health", err)
			middleware.Logger.Debug("/health function",
				zap.String("success_or_not", "error"),
			)
		}
	}()
	c.JSON(http.StatusOK, gin.H{"data": "接口调用成功!"})
}

func AlertEvents(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				middleware.Logger.Info("/AlertEvents function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()
	var thisEventSlicePoiter []*model.AlertEvent
	data, _ := ioutil.ReadAll(c.Request.Body)
	err3 := json.Unmarshal(data, &thisEventSlicePoiter)
	//获取告警信息
	for _, i := range thisEventSlicePoiter {
		count = count + 1
		util.InsertRedis(*i)
		fmt.Println("本地写到redis的第几条数据", count)
		middleware.Logger.Info("/AlertEvents message",
			zap.String("SystemAlias->", i.SystemAlias),
			zap.String("EventDatasource->", i.EventDatasource),
			zap.String("EventDatasourceName->", i.EventDatasourceName),
			zap.String("EventOccurIp->", i.EventOccurIp),
		)
	}
	if err3 != nil {
		middleware.Logger.Info("/AlertEvents Handler function json.Unmarshal error",
			zap.String("error_message->", err3.Error()),
		)
	}
	//业务代码....
	c.JSON(http.StatusOK, gin.H{
		"msg": "塞入告警中心成功!",
	})
}

func Common_alert(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				middleware.Logger.Info("/Common_alert function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()
	this_universalData := model.UniversalData{}
	data, _ := ioutil.ReadAll(c.Request.Body)
	err := json.Unmarshal(data, &this_universalData)
	if err != nil {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "AlertUniversalo Err", err)
	}
	var user_ids []string
	for _, this_receive_wechat_data := range this_universalData.Receive_wechat_names {
		user_id := util.GetRedisUserIdsByname(this_receive_wechat_data)
		user_ids = append(user_ids, user_id)
	}
	fmt.Println("user_ids", user_ids)
	// 2.格式化发送内容 3.邮箱发送
	email_template := util.UniversalPingjietemplate(this_universalData.Topic,
		"prod", this_universalData.Content, this_universalData.Ip, this_universalData.Caller, "通用告警", time.Now().Format("2006-01-02 15:04:05"), 1)
	email_err := util.SendMail(this_universalData.Topic, email_template, this_universalData.Receive_mails)
	if email_err != nil {
		fmt.Println("email_err", err)
	}
	//// 4.企业微信发送
	wechat_template := util.UniversalPingjietemplate(this_universalData.Topic,
		"prod", this_universalData.Content, this_universalData.Ip, this_universalData.Caller, "通用告警", time.Now().Format("2006-01-02 15:04:05"), 0)
	wechat_template_error := util.SendWeixin(wechat_template, user_ids)
	if wechat_template_error != nil {
		fmt.Println("wechat_template_error", err)
	}
	c.JSON(http.StatusOK, gin.H{
		"msg": "发送成功!",
	})
}

func AlertsubscriptionGet(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				middleware.Logger.Info("/AlertsendhistoryGet function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()
	Search := model.SearchSubscription{}
	data, _ := ioutil.ReadAll(c.Request.Body)
	json.Unmarshal(data, &Search)
	//根据域账号查询contact_id
	this_contact_id := 0
	for _, i := range middleware.ThisAlertcontact {
		my_str := strings.Split(i.Email, "@")[0]
		if my_str == Search.Username {
			this_contact_id = i.Contact_id
		}
	}
	//appname模糊查询app_ids
	var app_ids []int
	for _, zhaoapplication := range middleware.ThisZhaoapplication {
		if strings.Contains(zhaoapplication.Name, Search.Appname) {
			app_ids = append(app_ids, zhaoapplication.App_id)
		}
	}
	var subscription model.Subscription
	if (this_contact_id > 0) && (len(app_ids) > 0) {
		//根据contact_id和app_ids查询AlertsubscriptionGet
		subscription.Code = 200
		subscription.Msg = "success"
		subscription.ContactId = this_contact_id
		subscription.Total = 0
		var subscription_Datas []model.Subscription_data

		for _, app_id := range app_ids {
			for _, Alertsubscriptiondata := range middleware.ThisAlertsubscriptions {
				if (Alertsubscriptiondata.App_id == app_id) && (Alertsubscriptiondata.Contact_id == this_contact_id) {
					var thissubscription_data model.Subscription_data
					//打包此ways
					var ways []model.Ways
					for _, thisway := range middleware.ThisAlertways {
						if strings.Contains(Alertsubscriptiondata.Way_ids, strconv.Itoa(thisway.Way_id)) {
							var waydata model.Ways
							waydata.Way_id = thisway.Way_id
							waydata.Name = thisway.Name
							ways = append(ways, waydata)
						}
					}
					thissubscription_data.WayIds = ways
					thissubscription_data.Subid = Alertsubscriptiondata.Sub_id
					thissubscription_data.AppId = app_id
					thissubscription_data.AppName = middleware.GetAppNameByAppID(app_id)
					thissubscription_data.Pause = Alertsubscriptiondata.Pause
					thissubscription_data.Focus = Alertsubscriptiondata.Focus
					thissubscription_data.Black_words.String = Alertsubscriptiondata.Black_words
					thissubscription_data.Count = Alertsubscriptiondata.Count
					subscription_Datas = append(subscription_Datas, thissubscription_data)
				}
			}
		}
		subscription.Datas = subscription_Datas
		c.JSON(http.StatusOK, gin.H{
			"message": "OK",
			"code":    "0",
			"data":    subscription,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"msg":  "no data!",
			"code": "-1",
		})
	}
}

func Yunweiwayspause(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				middleware.Logger.Info("/Yunweiwayspause function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()
	yunweiPauseData := model.WaysPause{}
	data, _ := ioutil.ReadAll(c.Request.Body)
	err := json.Unmarshal(data, &yunweiPauseData)
	if err != nil {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), err)
	}
	if yunweiPauseData.Pause == 1 {
		util.Yunweiwayspause(true, yunweiPauseData.Name)
	} else if yunweiPauseData.Pause == 0 {
		util.Yunweiwayspause(false, yunweiPauseData.Name)
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":  "update success!",
		"code": "200",
	})
}

func Alertwayspause(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				middleware.Logger.Info("/Alertwayspause function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()
	alertPauseData := model.WaysPause{}
	data, _ := ioutil.ReadAll(c.Request.Body)
	err := json.Unmarshal(data, &alertPauseData)
	if err != nil {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), err)
	}
	if alertPauseData.Pause == 1 {
		util.Alertwayspause(true, alertPauseData.Name)
	} else if alertPauseData.Pause == 0 {
		util.Alertwayspause(false, alertPauseData.Name)
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":  "update success!",
		"code": "200",
	})
}

//更新运维方式的告警次数
func SubyunweiwaysCount(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				middleware.Logger.Info("/SubyunweiwaysCount function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()
	yunweicountData := model.WaysyunweiCount{}
	data, _ := ioutil.ReadAll(c.Request.Body)
	json.Unmarshal(data, &yunweicountData)
	for _, alertway := range middleware.ThisAlertways {
		for _, wayname := range yunweicountData.Waynames {
			if wayname == alertway.Name {
				ThisAlertObject := &model.Alertways{}
				middleware.DB.Model(ThisAlertObject).Where("name=?", wayname).Update("count", yunweicountData.Count)
			}
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "update count ok",
	})
}

func Alertwaysget(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				middleware.Logger.Info("/Alertwaysget function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()

	datas, have := util.Alertwaysget()
	if have {
		c.JSON(http.StatusOK, gin.H{
			"data":    datas,
			"code":    0,
			"message": "OK",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": "-1",
			"msg":  "查询失败",
		})
	}

}

func AlertsubscriptionDelete(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				middleware.Logger.Info("/AlertsubscriptionDelete function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()
	//重新更新应用订阅的信息
	defer middleware.GetAlertsubscriptionAllData()
	Sub := make(map[string]int)
	data, _ := ioutil.ReadAll(c.Request.Body)
	json.Unmarshal(data, &Sub)
	fmt.Println("Sub[\"subId\"]", Sub["subId"])
	util.DeleteSubscriptionByID(Sub["subId"])
	c.JSON(http.StatusOK, gin.H{
		"msg":  "delete success!",
		"code": "200",
	})
}

func AlertsubscriptionFocus(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				middleware.Logger.Info("/AlertsubscriptionFocus function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()
	//重新更新应用订阅的信息
	defer middleware.GetAlertsubscriptionAllData()
	Focus := make(map[string]int)
	data, _ := ioutil.ReadAll(c.Request.Body)
	json.Unmarshal(data, &Focus)
	if Focus["focus"] == 1 {
		util.UpdateSubscriptionFocusByID(Focus["subId"], true)
	} else {
		util.UpdateSubscriptionFocusByID(Focus["subId"], false)
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":  "update success!",
		"code": "200",
	})
}

func AlertsubscriptionPause(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				middleware.Logger.Info("/AlertsubscriptionPause function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()
	//重新更新应用订阅的信息
	defer middleware.GetAlertsubscriptionAllData()
	PauseData := make(map[string]int)
	data, _ := ioutil.ReadAll(c.Request.Body)
	json.Unmarshal(data, &PauseData)
	if PauseData["pause"] == 1 {
		util.UpdateSubscriptionPaueByID(PauseData["subId"], true)
	} else {
		util.UpdateSubscriptionPaueByID(PauseData["subId"], false)
	}
	c.JSON(http.StatusOK, gin.H{
		"msg":  "update success!",
		"code": "200",
	})
}

func AlertsubscriptionCount(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				middleware.Logger.Info("/AlertsubscriptionPause function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()
	//重新更新应用订阅的信息
	defer middleware.GetAlertsubscriptionAllData()
	var CountData model.CountData
	data, _ := ioutil.ReadAll(c.Request.Body)
	json.Unmarshal(data, &CountData)
	fmt.Println("CountData", CountData)
	util.UpdateSubscriptionCount(CountData.AppName, CountData.Username, CountData.Count)
	c.JSON(http.StatusOK, gin.H{
		"msg":  "update success!",
		"code": "200",
	})
}

func Alertsubscriptionblackwords(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				middleware.Logger.Info("/Alertsubscriptionblackwords function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()
	//重新更新应用订阅的信息
	defer middleware.GetAlertsubscriptionAllData()
	blackwords := make(map[string]string)
	data, _ := ioutil.ReadAll(c.Request.Body)
	json.Unmarshal(data, &blackwords)
	fmt.Println("blackwords", blackwords)
	util.UpdateSubscriptionblackwords(blackwords["appName"], blackwords["username"], blackwords["blackwords"])
	c.JSON(http.StatusOK, gin.H{
		"msg":  "update success!",
		"code": "200",
	})
}

func Alertsubscrblackworddelete(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				middleware.Logger.Info("/Alertsubscrblackworddelete function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()
	//重新更新应用订阅的信息
	defer middleware.GetAlertsubscriptionAllData()
	blackwords := make(map[string]string)
	data, _ := ioutil.ReadAll(c.Request.Body)
	json.Unmarshal(data, &blackwords)
	util.UpdateSubdelteblackwords(blackwords["appName"], blackwords["username"], blackwords["blackwords"])
	c.JSON(http.StatusOK, gin.H{
		"msg":  "update success!",
		"code": "200",
	})
}

func AlertsubscriptionAdd(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				middleware.Logger.Info("/AlertsubscriptionPause function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()
	//重新更新应用订阅的信息
	defer middleware.GetAlertsubscriptionAllData()
	var SubScriptioData model.AddSubscriptionData
	data, _ := ioutil.ReadAll(c.Request.Body)
	json.Unmarshal(data, &SubScriptioData)
	fmt.Println("插入的数据是", SubScriptioData.Appname, SubScriptioData.Username, SubScriptioData.Wayids)
	util.SubsriptionAdd(SubScriptioData.Appname, SubScriptioData.Username, SubScriptioData.Wayids)
	c.JSON(http.StatusOK, gin.H{
		"msg":  "update success!",
		"code": "200",
	})
}
